<?php

class SiteController extends GTL_Action {

    public function init() {
        parent::init();
        /* Initialize action controller here */

        //set session key
        $this->list_sess_unset('controller_site');
        $this->session_search_key = 'controller_site';
        $this->session_search_name = 'search_label';

        if ($this->_getParam('site_id') && $this->_getParam('site_id') != "") {
            $site_id = $this->_getParam('site_id');
            $siteModel = new Model_Site();
            $sitedata = $siteModel->fetchEntryByViewId($site_id, $this->USER->usr_lang_id);
            if($this->USER->role != 'ADMIN'){
                if($sitedata['com_id'] != $this->USER->company_id){
                    $this->_helper->redirector('list', 'site', '');
                }
            }
        }
            
        
    }

    public function indexAction() {
        $this->_helper->redirector('list', 'site', '');
    }

    public function viewAction() {
        if ($this->_getParam('site_id') && $this->_getParam('site_id') != "") {
            $site_id = $this->_getParam('site_id');
        } else {
            $this->_helper->redirector('list', 'site', '');
        }
        $siteModel = new Model_Site();
        $sitehoursModel = new Model_Sitehours();
        $sitedata = $siteModel->fetchEntryByViewId($site_id, $this->USER->usr_lang_id);
        $updated_id = $sitedata['lgn_id'];
        $login_type = $sitedata['lgn_type'];

        /*         * get user name which is updated data* */
        $loginModel = new Model_Login();
        $updated_by_user = $loginModel->getUserData(Array('lgn_id' => $updated_id));
        $user_name = ucfirst($updated_by_user->name) . " [" . ucfirst($updated_by_user->role) . "]";

        //site hours data
        $sitehoursData = $sitehoursModel->fetchEntryBysiteId($site_id);
        $weekArray = $siteModel->getweekArray();
        $hoursArray = $siteModel->gethoursArray();
        $minutesArray = $siteModel->getminutesArray();

        $this->view->sitehoursData = $sitehoursData;

        $this->view->weekarray = $weekArray;
        $this->view->hoursarray = $hoursArray;
        $this->view->minutesarray = $minutesArray;
        $this->view->admindata = $user_name;
        $this->view->sitedata = $sitedata;
    }

    public function listAction() {

        $errorMessage = Array();
        $successmessage = "";
        $where = "1=1 ";
        $searchtype = "";
        $orderField = 'site_id';
        $sort = 'asc';
        if (!isset($_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name])) {
            $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name] = "";
        }

        /* Pagination Login */
        $itemsPerPageReviews = $this->PAGING_PER_PAGE;
        $currentPageReviews = 1;

        //PAGING_PER_PAGE

        if ($this->_getParam('page') && $this->_getParam('page') != "") {
            $currentPageReviews = $this->_getParam('page');
        }

        if ($this->_getParam('field') && $this->_getParam('field') != "") {
            $orderField = $this->_getParam('field');
        }

        if ($this->_getParam('sort') && $this->_getParam('sort') != "") {
            $sort = $this->_getParam('sort');
        }

        $offset = ($currentPageReviews - 1) * $itemsPerPageReviews;
        if ($this->_request->isPost()) {
            $postedData = $this->_request->getPost();

            //Multiple Delete Logic 
            if (isset($postedData["multiaction"]) && ($postedData["multiaction"] != "")) {
                $action = trim($postedData["multiaction"]);
                if (isset($postedData["multicheck"]) && count($postedData["multicheck"]) > 0) {
                    $ids = implode(",", $_POST["multicheck"]);
                    $result = $this->deleteAction($_POST["multicheck"]);
                } else {
                    $errorMessage[] = $this->ZFTRANSLATE->translate("select_one_checkbox");
                }
            }

            /* Search Facility Over Here */
            if ($postedData["searchtype"] == "") {
                $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name] = "";
            }
            if (isset($postedData["searchtype"]) && ($postedData["searchtype"] != "")) {
                $searchtype = $postedData["searchtype"];
                $where = "site_name LIKE '%$searchtype%' OR  com_name LIKE '%$searchtype%' OR  site_email LIKE '%$searchtype%'";
                $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name] = $searchtype;
                $this->view->searchtype = $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name];
            }
        } else {
            $searchtype = $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name];
            if ($searchtype != '') {
                $where = "site_name LIKE '%$searchtype%'  OR com_name LIKE '%$searchtype%' OR  site_email LIKE '%$searchtype%'";
                $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name] = $searchtype;
                $this->view->searchtype = $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name];
            }
        }

        if ($this->USER->roletype == 'Contractor' || $this->USER->roletype == 'SuperContractor' ||
                $this->USER->roletype == 'Customer' || $this->USER->roletype == 'SuperCustomer') {
            $where .=' ) AND (site.com_id=' . $this->USER->company_id;
        } else {
            $where .='';
        }

        if ($this->_getParam('com_id') && $this->_getParam('com_id') != "") {
            $where .= ")AND (site.com_id = '" . $this->_getParam('com_id') . "'";
        }

        $siteModel = new Model_Site();


        $sitesData = $siteModel->fetchSite($where, $itemsPerPageReviews, $offset, $orderField, $sort);

        $paginator = new GTL_Paginator();
        $paginator->setItemsPerPage($itemsPerPageReviews);
        $paginator->setItemsTotal($siteModel->getSiteCount($where));
        $paginator->setCurrentPage($currentPageReviews);
        $link = $this->view->url(array('controller' => 'site', 'action' => 'list', 'page' => 'PAGENO'), 'default', false);
        $paginator->paginate($link);

        $this->view->paginator = $paginator;
        $this->view->sitesData = $sitesData;
        $this->view->errorMessage = $errorMessage;
        $this->view->successmessage = $successmessage;
        $this->view->statusArray = $siteModel->getStatusArray();
        $this->view->searchtype = $searchtype;
    }

    public function deleteAction($ids = Array()) {
        //Load Site Model 
        $siteModel = new Model_Site();
        if ($this->_getParam('site_id') && $this->_getParam('site_id') != "") {
            $site_id = $this->_getParam('site_id');
            $siteModel->deleteSite($site_id);
            $this->addSuccessMessage($this->ZFTRANSLATE->translate("site_delete_success"));
            $this->_helper->redirector('list', 'site', '');
        } else {
            $siteModel->deleteSite($ids);
            $this->addSuccessMessage($this->ZFTRANSLATE->translate("site_delete_success"));
            $this->_helper->redirector('list', 'site', '');
        }
    }

    public function formAction() {

        //Initialize
        $successmessage = "";
        $errorMessageArray = Array();
        $data = array();
        $siteData = Array();
        $this->view->mode = "Add";



        //Load Site Model
        $siteModel = new Model_Site();
        //Load Site Form
        $siteForm = new Form_SiteForm();
        $imageName = "";

        $sitehoursModel = new Model_Sitehours();

        $weekArray = $siteModel->getweekArray();
        $hoursArray = $siteModel->gethoursArray();
        $minutesArray = $siteModel->getminutesArray();



        //Load the country array for the select box in form 
        $countryArray = $siteModel->getcountryArray();
        $siteForm->site_country->addMultiOptions($countryArray);

        //Load the company array for the select box in form 
        $companyArray = $siteModel->getcompanyArray();
        $siteForm->com_id->addMultiOptions($companyArray);

        //Load the guard array for the select box in form 
        $guardArray = $siteModel->getguardArray();
        $siteForm->site_guard->addMultiOptions($guardArray);

        //Load the keysafe array for the select box in form 
        $keysafeArray = $siteModel->getkeysafeArray();
        $siteForm->site_keysafe->addMultiOptions($keysafeArray);


        //Load the quality array for the select box in form 
        $typeArray = $siteModel->gettypeArray($this->USER->usr_lang_id);
        $siteForm->type_id->addMultiOptions($typeArray);


        //Load the status array for the select box in form 
        $statusArray = $siteModel->getStatusArray();
        $siteForm->site_status->addMultiOptions($statusArray);

        //Load the unit array for the select box in form 
        //Check for the site Parameter
        $siteData['site_id'] = $this->_request->getParam('site_id');
        $site_id = (!empty($siteData['site_id'])) ? $siteData['site_id'] : null;

        if (!empty($site_id)) {
            //Set the Mode to Edit
            $this->view->mode = "Edit";
            //Fetch data to be loaded in form 
            $data = $siteModel->fetchEntryById($site_id);
            $sitehoursData = $sitehoursModel->fetchEntryBysiteId($site_id);
            $this->view->sitehoursData = $sitehoursData;
            $this->view->imageName = $data['site_map'];
        }

        //Populate form 
        $this->view->form = $siteForm->populate($data);
        if ($this->getRequest()->isPost()) {

            //Check for Errors
            $postedData = $this->_request->getPost();
            if (array_key_exists('site_hr_day', $postedData)) {
                if ($postedData['site_hr_day'] != "" || $postedData['site_hr_commision_hr'] != "" || $postedData['site_hr_commision_mint'] != "" || $postedData['site_hr_decommision_hr'] != "" || $postedData['site_hr_decommision_mint'] != "" || $postedData['site_hr_date'] != "") {
                    foreach ($postedData['site_hr_day'] as $key => $value) {
                        $sitehoursData[$value]['site_hr_day'] = $value;
                        $sitehoursData[$value]['site_hr_commision_hr'] = $postedData['site_hr_commision_hr'][$key];
                        $sitehoursData[$value]['site_hr_commision_mint'] = $postedData['site_hr_commision_mint'][$key];
                        $sitehoursData[$value]['site_hr_decommision_hr'] = $postedData['site_hr_decommision_hr'][$key];
                        $sitehoursData[$value]['site_hr_decommision_mint'] = $postedData['site_hr_decommision_mint'][$key];
                        $sitehoursData[$value]['site_hr_date'] = $postedData['site_hr_date'][$key];
                    }
                    $this->view->sitehoursData = $sitehoursData;
                    // echo '<pre>';print_r($sitehoursData);exit;
                }
            }




            if ($this->view->mode == 'Edit') {
                
            }
            if (!$siteForm->isValid($postedData)) {
                $errorMessage = $siteForm->getMessages();
                foreach ($errorMessage as $_err) {
                    foreach ($_err as $_val) {
                        $errorMessageArray[] = $_val;
                    }
                }
            } else {
                if (count($errorMessageArray) > 0) {
                    
                } else {
                    if ($this->view->mode == "Add") {
                        $SiteCount = $siteModel->getSiteCount('');
                        $siteData['site_createddate'] = date("Y-m-d H:i:s");
                    }
                    $sitehoursData = array();

                    //Image upload
                    $upload = new Zend_File_Transfer_Adapter_Http();
                    foreach ($upload->getFileInfo() as $fields => $asFileInfo) {
                        if ($asFileInfo['name'] != '') {
                            $folder = $this->config->UPLOAD_PATH . "site/";
                            $upload->setDestination($folder);
                            $originalFilename = pathinfo($asFileInfo['name']);
                            $fileName = preg_replace("/[^-_a-zA-Z0-9]+/i", "_", $originalFilename['filename']) . '_' . time() . '.' . $originalFilename['extension'];
                            $upload->addFilter('Rename', $fileName, 'filename');
                            $upload->receive($fields);
                            $siteData['site_map'] = $fileName;
                        }
                    }

                    /* if($postedData['site_id'] != ""){
                      $sitehoursData = $sitehoursModel->fetchEntryBysiteId($postedData['site_id']);
                      $this->view->sitehoursData =$sitehoursData;
                      } */
                    /*                     * authentication login id */

                    $updated_userid = $this->USER->lgn_id;

                    //Site save
                    $siteData['updated_lgn_id'] = $updated_userid;
                    $siteData['site_id'] = $site_id;
                    $siteData['com_id'] = $postedData['com_id'];
                    $siteData['type_id'] = $postedData['type_id'];
                    $siteData['site_name'] = $postedData['site_name'];
                    $siteData['site_address'] = $postedData['site_address'];
                    $siteData['site_postal_code'] = $postedData['site_postal_code'];
                    $siteData['site_city'] = $postedData['site_city'];
                    $siteData['site_country'] = $postedData['site_country'];
                    $siteData['site_phone_1'] = $postedData['site_phone_1'];
                    $siteData['site_phone_2'] = $postedData['site_phone_2'];
                    $siteData['site_phone_3'] = $postedData['site_phone_3'];
                    $siteData['site_email'] = $postedData['site_email'];
                    $siteData['site_guard'] = $postedData['site_guard'];
                    $siteData['site_digicode'] = $postedData['site_digicode'];
                    $siteData['site_keysafe'] = $postedData['site_keysafe'];
                    $siteData['site_code'] = $postedData['site_code'];
                    $siteData['site_status'] = $postedData['site_status'];
                    $siteData['site_key_safe_loc'] = $postedData['site_key_safe_loc'];
                    $siteData['site_vulnerabilities'] = $postedData['site_vulnerabilities'];
                    $siteData['site_updateddate'] = date("Y-m-d H:i:s");

                    $site_id = $siteModel->save($siteData, 'site_id');



                    $sitehoursData = array();
                    $sitehoursData['site_id'] = $site_id;

                    $sitehoursModel->delete("site_id = '" . $site_id . "'");
                    foreach ($postedData['site_hr_day'] as $siteKey => $siteValue) {

                        $sitehoursData['site_hr_day'] = $siteValue;
                        $sitehoursData['site_hr_commision_hr'] = $postedData['site_hr_commision_hr'][$siteKey];
                        $sitehoursData['site_hr_commision_mint'] = $postedData['site_hr_commision_mint'][$siteKey];
                        $sitehoursData['site_hr_decommision_hr'] = $postedData['site_hr_decommision_hr'][$siteKey];
                        $sitehoursData['site_hr_decommision_mint'] = $postedData['site_hr_decommision_mint'][$siteKey];
                        $sitehoursData['site_hr_date'] = $postedData['site_hr_date'][$siteKey];
                        $sitehoursData['updated_lgn_id'] = $updated_userid;
                        $sitehoursModel->save($sitehoursData, 'site_hr_id');
                    }



                    if ($this->view->mode == "Add") {
                        $successmessage = $this->ZFTRANSLATE->translate("site_add_success");
                    } else {
                        $successmessage = $this->ZFTRANSLATE->translate("site_update_success");
                    }
                    $this->addSuccessMessage($successmessage);
                    $this->_helper->redirector('list', 'site', '');
                }
            }
        }
        $this->view->weekarray = $weekArray;
        $this->view->hoursarray = $hoursArray;
        $this->view->minutesarray = $minutesArray;
        $this->view->mode = $this->view->mode;
        $this->view->siteid = $site_id;
        // $this->view->imageName = $imageName;
        $this->view->errorMessageArray = $errorMessageArray;
        $this->view->succesMessage = $successmessage;
        $this->view->form = $siteForm;
    }

    public function downloadAction() {
        $siteModel = new Model_Site();
        $site_id = $this->_getParam('site_id');
        $siteArray = $siteModel->fetchEntryById($site_id);
        $document_name = $siteArray['site_map'];
        $file = $this->config->UPLOAD_PATH . "site/" . $document_name;
        $gtlObj = new GTL_Common();
        $download_file = $gtlObj->dl_file($file);
    }

}

?>
